package cn.xtits.xtf.common.utils;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.junit.Test;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;

public class BeanUtil {

    public static Object getValue(Object obj,String propertyName) {
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if(name.equals(propertyName)) {
                    if (!"class".equals(name)) {
                        System.out.println(name + ":" + propertyUtilsBean.getNestedProperty(obj, name));
                        return  propertyUtilsBean.getNestedProperty(obj, name);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }


    public static void  test2(Object obj) {
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    System.out.println(name+":"+ propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void testReflect(Object model) throws Exception{
        for (Field field : model.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            System.out.println(field.getName() + ":" + field.get(model) );
        }
    }

    @Test
    public void  test() throws Exception {
        Exception exception=new Exception("1");
        System.out.println(getValue(exception,"message"));
        testReflect(exception);
    }
}
